package com.example.szojcodesandbox.template;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.example.szojcodesandbox.model.ExecuteCodeRequest;
import com.example.szojcodesandbox.model.ExecuteCodeResponse;
import com.example.szojcodesandbox.model.ExecuteMessage;
import com.example.szojcodesandbox.model.JudgeInfo;
import com.example.szojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public abstract class JavaCodeSandboxTemplate implements CodeScandbox{
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    private static final long TIME_OUT = 5000L;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        //1、将代码保存为文件
        File userCodeFile = saveCodeToFile(code);

        //2、编译代码 得到class文件
        ExecuteMessage complieFileExecuteMessage = compileFile(userCodeFile);
        System.out.println(complieFileExecuteMessage);

        //3、执行代码输出结果
        List<ExecuteMessage> executeMessageList= runFile(userCodeFile,inputList);

        //4、收集整理输出结果
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessageList);

        //5、文件清理
        boolean b =deleteFile(userCodeFile);
        if(!b){
            log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsolutePath());
        }
        return outputResponse;
    }

    /**
     * 获取错误响应
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e){
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        //表示沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }

    /**
     * 删除文件
     * @param userCodeFile
     * @return
     */
    private boolean deleteFile(File userCodeFile) {
        if(userCodeFile.getParentFile() !=null){
            String userCodeParenPath = userCodeFile.getParentFile().getAbsolutePath();
            boolean del = FileUtil.del(userCodeParenPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }

    /**
     * 输出执行结果
     * @param executeMessageList
     * @return
     */
    private ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> executeMessageList) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        //取用时最大值
        long maxTime = 0;
        for(ExecuteMessage executeMessage:executeMessageList){
            String errorMessage = executeMessage.getErrorMessage();
            if(StrUtil.isNotBlank(errorMessage)){
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if(time != null){
                maxTime = Math.max(maxTime,time);
            }
        }
        //正常运行完成
        if(outputList.size() == executeMessageList.size()){
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        //需要借助第三方库获取内存
        //TODO
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 执行文件，获取结果
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        AtomicBoolean finished = new AtomicBoolean(false);
        List<ExecuteMessage> executeMessagesList = new ArrayList<>();
        for(String inputArgs : inputList){
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",userCodeParentPath,inputArgs);
            try {
                Process exec = Runtime.getRuntime().exec(runCmd);
                new Thread(()->{
                    try{
                        Thread.sleep(TIME_OUT);
                        if (!finished.get() && exec.isAlive()) {
                            System.out.println("超时");
                            exec.destroy();
                        }
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start();
                //ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(exec, "运行");
                ExecuteMessage executeMessage = ProcessUtils.runInteractProcessAndGetMessage(exec, inputArgs);
                System.out.println(executeMessage);
                executeMessagesList.add(executeMessage);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        return executeMessagesList;
    }

    /**
     * 编译代码
     * @param userCodeFile
     * @return
     */
    private ExecuteMessage compileFile(File userCodeFile) {
        String compiledCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            Process exec = Runtime.getRuntime().exec(compiledCmd);
           ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(exec, "编译");
            if(executeMessage.getExitValue()!= 0){
                throw new RuntimeException("编译错误");
            }
            return executeMessage;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 保存用户代码到文件
     * @param code
     * @return
     */
    private File saveCodeToFile(String code) {
        String userDir = System.getProperty("user.dir");
        String  globalCodePathName=userDir+File.separator+ GLOBAL_CODE_DIR_NAME;
        if(!FileUtil.exist(globalCodePathName)){
            FileUtil.mkdir(globalCodePathName);
        }

        //将用户代码隔离存放
        String userCodeParenPath = globalCodePathName+File.separator+ UUID.randomUUID();
        String userCodePath = userCodeParenPath + File.separator+GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code,userCodePath, StandardCharsets.UTF_8);
        return userCodeFile;
    }

}
